package org.jimmy.test.sample;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * Hello world!
 * 
 */
public class App
{
	private static final String JPG = "jpg";
	private static final int IMG_WIDTH = 100;
	private static final int IMG_HEIGHT = 100;

	public static void main(String[] args)
	{
		final String srcFileName = args[0];
		try
		{
			FileInputStream input = new FileInputStream(srcFileName);

			BufferedImage originalImage = ImageIO.read(input);
			int type = originalImage.getType() == BufferedImage.TYPE_CUSTOM ? BufferedImage.TYPE_INT_ARGB
					: originalImage.getType();

			long startTime = System.currentTimeMillis();
			BufferedImage resizeImageJpg = resizeImage(originalImage, type);
			long endTime = System.currentTimeMillis();

			System.out.println("resize time spent:" + (endTime - startTime));

			FileOutputStream output = new FileOutputStream(srcFileName + "_"
					+ IMG_WIDTH + "_" + IMG_HEIGHT + "." + JPG);
			ImageIO.write(resizeImageJpg, JPG, output);

		}
		catch (IOException e)
		{
			System.out.println(e.getMessage());
		}

	}

	private static BufferedImage resizeImage(BufferedImage originalImage,
			int type)
	{
		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
				type);
		Graphics2D g = resizedImage.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_SPEED);
		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
		g.dispose();

		return resizedImage;
	}

	private static BufferedImage resizeImageWithHint(
			BufferedImage originalImage, int type)
	{

		BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
				type);
		Graphics2D g = resizedImage.createGraphics();

		g.setComposite(AlphaComposite.Src);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);

		g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);

		g.dispose();

		return resizedImage;
	}
}
